package cn.jiangjiesheng.bootstrap.gateway.commons;

import com.alibaba.fastjson.JSONPath;
import com.google.common.collect.Lists;
//import com.qpaas.sdk.user.LoginRequest;
import cn.jiangjiesheng.bootstrap.commons.response.ResponseWrapper;
//import cn.jiangjiesheng.bootstrap.qpaas.PaasTemplate;
//import cn.jiangjiesheng.bootstrap.qpaas.legacy.PlatformService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseCookie;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * Created by dev@jiangjiesheng.cn on 2022/5/17  <br/>
 *
 * @author dev@jiangjiesheng.cn
 */
@Slf4j
@Controller
@RequestMapping("/shengxingapi/user")
public class UserController {
//
//    @Autowired
//    private PlatformService platformService;
//
//    @Autowired
//    private PaasTemplate paasTemplate;

    @Autowired
    private UserService userService;

    @GetMapping("prolongSessionLife")
    @ResponseBody
    public ServerResponse prolongSessionLife(@CookieValue(required = false, value = "access_token") String accessToken,
                                             @RequestHeader(value = "domain", required = false) String domain) {
//        final Map<String, Object> returning = platformService.prolongSessionLife(StringUtils.trim(accessToken), true);
//        List<ResponseCookie.ResponseCookieBuilder> cookies = Lists.newArrayList(ResponseCookie.from("access_token",
//                        returning.get("accessToken").toString()),
//                ResponseCookie.from("PHPSESSID",
//                        returning.get("accessToken").toString()));
//        final ServerResponse.BodyBuilder bodyBuilder = ServerResponse.ok().contentType(MediaType.APPLICATION_JSON);
//        for (ResponseCookie.ResponseCookieBuilder cookie : cookies) {
//            cookie.maxAge(14 * 24 * 60 * 60);
//            cookie.secure(true);
//            cookie.domain(domain.replace("www", ""));
//            cookie.path("/");
//            cookie.httpOnly(false);
//            bodyBuilder.cookie(cookie.build());
//        }
//        return bodyBuilder.body(BodyInserters.fromValue(returning)).block();
        ServerResponse.BodyBuilder bodyBuilder = ServerResponse.ok().contentType(MediaType.APPLICATION_JSON);
        return bodyBuilder.body(BodyInserters.fromValue("")).block();
    }

    /**
     * 登录接口
     *
     * @param loginModel1
     * @return
     */
    @ResponseBody
    @PostMapping(value = "login", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Mono<MultiValueMap<String, String>> login(@ModelAttribute MultiValueMap<String, String> loginModel1) {
        return Mono.just(loginModel1).doOnNext(loginModel -> {
            Objects.requireNonNull(loginModel);
//            LoginRequest loginRequest = new LoginRequest();
//            loginRequest.setUserId(loginModel.get("username").toString());
//            loginRequest.setPassword(loginModel.get("password").toString()); // 对应用户的登录账号密码
//            loginRequest.setVerifyTwo(false); // 是否考虑用户两不验证设置
//            loginRequest.setDebug(true); //打开日志
//            final PaasTemplate.PaasResultForList result = paasTemplate.executeForList(loginRequest);
//            String token = JSONPath.read(result.toString(), "$[0]").toString();
//            loginModel.set("password", "");
//            loginModel.set("token", token);
        }).doOnError((e) -> {
            log.error("登录出错 {}", e);
        });
    }

    /**
     * 使用前需要申请对应用户的开发者key
     *
     * @param userId
     * @return
     */
    @ResponseBody
    @GetMapping("/loginById")
    public ServerResponse getAccessTokenByUserId(@RequestParam("userId") String userId, @RequestParam("accessKey") String accessKey) {
        final ServerResponse.BodyBuilder bodyBuilder = ServerResponse.ok().contentType(MediaType.APPLICATION_JSON);
        if (!userService.hasValidDevelopKey(userId)) {
            return bodyBuilder.body(BodyInserters.fromValue(
                    ResponseWrapper.builder().success(false)
                            .message("未配置开发者key，请检查shengxing-commons.yaml的paas.develop项").build()
            )).block();
        }
        if (!Objects.equals(userService.getAccessKey(), accessKey)) {
            return bodyBuilder.body(BodyInserters.fromValue(
                    ResponseWrapper.builder().success(false)
                            .message("accessKey不正确").build()
            )).block();
        }
        return bodyBuilder.body(BodyInserters.fromValue(
                        ResponseWrapper.builder().success(true)
                                .result(userService.getAccessTokenByLoginId(userId)).build()
                )
        ).block();
    }

}
